package com.library.controller;

import com.library.dto.pojo.excelPo.ReaderExportInfo;
import com.library.dto.pojo.excelPo.ReaderImportInfo;
import com.library.service.IReaderService;
import com.library.utils.excelUtils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 至尊伍人组
 * @since 2018-09-30
 */
@Controller
@RequestMapping ( "/reader" )
public class ReaderController {

    @Autowired
    IReaderService readerService;

    @RequestMapping ( "/test" )
    public String test() {
        return "reader/reader";
    }

    @RequestMapping ( "/del/{readerId}" )
    public String del( @PathVariable int readerId ) {

        readerService.deleteById(readerId);

        return "redirect:/admin/readermanager";
    }

    /**
     * 读取(解析)Excel（允许多个 sheet）
     */
    //    @ResponseBody
    @RequestMapping ( value = "readExcel", method = RequestMethod.POST )
    public String readExcel( @RequestParam ( "file" ) MultipartFile excel ) {
        List<Object> objects = ExcelUtil.readExcel(excel, new ReaderImportInfo());

        readerService.insertBatchFromExcel(objects);

        return "redirect:/admin/readermanager";
    }

    /**
     * 导出 Excel（一个 sheet）
     */
    @ResponseBody
    @RequestMapping ( value = "/writeExcel", method = RequestMethod.GET )
    public void writeExcel( HttpServletResponse response ) throws IOException {

        //获得图书的所有记录列表
        List<ReaderExportInfo> list = null;
        list = readerService.getReaderExcelList();
        //        bookService.getBookExcelList();

        String s = LocalDateTime.now().toString();
        String timeStamp = s.substring(0, s.indexOf("T"));
        String fileName = timeStamp + "读者信息";
        String sheetName = "读者信息";

        ExcelUtil.writeExcel(response, list, fileName, sheetName, new ReaderExportInfo());
    }
}

